package com.forest.core.widget.dialog

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.*
import androidx.appcompat.app.AppCompatDialogFragment
import com.ysyc.core.R


/**
 *    author : duanguosen
 *    date   : 2019/12/3
 *    desc   :
 */
abstract class FBaseDialog : AppCompatDialogFragment() {

     var options = Options()

//    fun setOptions(options: Options){
//        this.options = options
//    }
//
//    fun getOptions() = options

    private var rootView: View? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        when {
            options.layoutRes != 0 -> {
                //调用方通过xml获取view
                rootView = inflater.inflate(options.layoutRes, container, false)
            }
            options.dialogView != null -> {
                //调用方直接传入view
                rootView = options.dialogView
            }
            else -> {
                options.layoutRes = R.layout.layout_ydialog_default
                rootView = inflater.inflate(options.layoutRes, container, false)
            }
        }
        return rootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        dialog?.apply {
            requestWindowFeature(Window.FEATURE_NO_TITLE)
            setCancelable(options.isCancelable)
            setCanceledOnTouchOutside(options.isCancelableOutside)
            setOnKeyListener { _, keyCode, event ->
                return@setOnKeyListener keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN && !options.isCancelable
            }
        }
    }

    override fun onStart() {
        super.onStart()
        dialog?.apply {
            window?.apply {
                if (options.isTransparent) {
                    setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
                }
                val windowParams = attributes
                windowParams.width = options.dialogWidth
                windowParams.height = options.dialogHeight
                windowParams.dimAmount = options.dimAmount
                windowParams.gravity = options.gravity
                attributes = windowParams
            }
        }
    }



    protected fun getRootView() = rootView

}